package com.kevin.swing.impl;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

import lombok.extern.log4j.Log4j;

import com.kevin.MainFrame;
import com.kevin.model.db.DBTableModel;
import com.kevin.model.jtable.JTableModel;
import com.kevin.swing.CWCheckBoxRenderer;
import com.kevin.swing.CheckBoxCellEditor;
import com.kevin.swing.ContentJPanel;
import com.kevin.util.CacheUtil;
import com.kevin.util.ConfigProperties;
import com.kevin.util.JTableUtil;
import com.kevin.util.Utils;

@Log4j
public class ContentStep1JPanel extends ContentJPanel {

    private static final long serialVersionUID = 4865803795120029379L;

    // 右键
    private JPopupMenu popup = new JPopupMenu();
    private JMenuItem openfItem = new JMenuItem("生成实体类");

    private JLabel searchKeyLabel = new JLabel("表名：");
    private JTextField searchText = new JTextField();// 搜素关键字
    private JButton searchBtn = new JButton("搜索表");// 选择

    private Boolean canStopSearch = false;
    private int searchNum = 0; // 搜索条目
    private SwingWorker<Long, Void> worker;

    private List<DBTableModel> tableList = new ArrayList<>();
    private List<String> selectedTables = new ArrayList<>(); // 选中的表名

    public ContentStep1JPanel(MainFrame owner) {
        super(owner);
        init();
    }

    protected void init() {
        popup.add(openfItem);
        openfItem.addActionListener(e -> {
        });

        setPanel();
    }

    protected void setPanel() {
        logTA = new JTextArea();
        logTA.setLineWrap(true);
        showlog("请先输入表名进行查询。");
        logTA.setBorder(null);
        jsplogTA = new JScrollPane(logTA);
        initJTable();
        setTableColumWidth();
        addTableAction();

        showtableJSpane = new JScrollPane(showTable);
        showtableJSpane.setPreferredSize(new Dimension(600, 69));

        addSearchAction(); // 搜索表

        // 搜索触发事件
        addSearchTextListener();

        JPanel searchbtnPanel = new JPanel();
        searchbtnPanel.setLayout(new GridBagLayout());
        searchbtnPanel.add(searchKeyLabel, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
                new Insets(0, 0, 0, 0), 0, 0));
        searchbtnPanel.add(searchText, new GridBagConstraints(4, 0, 2, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
                new Insets(0, 0, 0, 0), 0, 0));
        JPanel searchPanel = new JPanel();
        searchPanel.add(searchBtn);
        searchbtnPanel.add(searchPanel, new GridBagConstraints(6, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
                new Insets(0, 0, 0, 0), 0, 0));

        setLayout(new BorderLayout());
        add(searchbtnPanel, BorderLayout.NORTH);
        add(showtableJSpane, BorderLayout.CENTER);
        add(jsplogTA, BorderLayout.SOUTH);

    }

    /**
     * 搜索表
     * 
     * @Title addSearchAction
     * @author 吕凯
     * @date 2016年8月23日 下午3:23:16 void
     */
    private void addSearchAction() {
        searchBtn.addActionListener(e -> {
            if (canStopSearch) {
                showlog("正在停止搜索……");
                searchBtn.setEnabled(false);
            } else {
                // 搜索
                worker = new SwingWorker<Long, Void>() {

                    @Override
                    protected void done() {
                        searchDone();
                    }

                    @Override
                    protected Long doInBackground() {
                        try {
                            long ts = System.currentTimeMillis();
                            showlog("搜索中……");
                            searchBtn.setText("停止");
                            canStopSearch = true;

                            resetSearchTable();
                            String searchkey = searchText.getText(); //
                            tableList = owner.getDbTableService().getTables(searchkey);
                            tableList.forEach(table -> addTableRow(table));
                            owner.setSearchTables(tableList); // 赋给父容器

                            CacheUtil.put(ConfigProperties.CACHE_STEP1_TABLE, tableList);

                            long te = System.currentTimeMillis();
                            showlog("搜索到表" + tableList.size() + "条，共用时" + Utils.timeFormat(te - ts) + "，请选择表进行下一步操作！");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                };
                worker.execute();

            }
        }); // 添加事件处理
    }

    /**
     * 搜索时重置表格内容
     * 
     * @Title resetSearchTable
     * @author 吕凯
     * @date 2016年8月23日 下午3:56:29 void
     */
    private void resetSearchTable() {
        selectedTables.clear();
        index = 0;
        showTableModel = new DefaultTableModel(JTableModel.DEFAULTINFO_STEP1, JTableModel.COLNAMES_STEP1);
        showTable.setModel(showTableModel);
        setTableColumWidth();
    }

    /**
     * 搜索表返回内容容器jtable初始化
     * 
     * @Title initJTable
     * @author 吕凯
     * @date 2016年8月23日 下午3:23:27 void
     */
    private void initJTable() {
        showTableModel = new DefaultTableModel(JTableModel.DEFAULTINFO_STEP1, JTableModel.COLNAMES_STEP1);
        showTable = new JTable(showTableModel) {
            private static final long serialVersionUID = 1234567L;

            // 不可编辑
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }

            @Override
            public Rectangle getCellRect(int row, int column, boolean includeSpacing) {
//                if (row % 2 == 1) {// 偶数行特殊处理合并
//                    Rectangle rect = new Rectangle(0, this.getRowHeight() * row, this.getWidth(), this.getRowHeight());
//
//                    // repaint();
//                    return rect;
//                }

                return super.getCellRect(row, column, includeSpacing);
            }

        };
        try {
            List<DBTableModel> jsonTables = getTableCache();
            if (jsonTables != null && jsonTables.size() > 0) {
                tableList = jsonTables;
                owner.setSearchTables(tableList); // 赋给父容器
                tableList.forEach(table -> addTableRow(table));
                showlog("搜索到表" + tableList.size() + "条" + "，请选择表进行下一步操作！");
            }
        } catch (Exception e) {
            log.warn("转换实时访问数据出错", e);
        }
        TableColumnModel tcm = showTable.getColumnModel();
        tcm.getColumn(1).setCellEditor(new CheckBoxCellEditor());
        tcm.getColumn(1).setCellRenderer(new CWCheckBoxRenderer());
        // 添加标格监听事件
        showTable.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    int columnIndex = showTable.columnAtPoint(e.getPoint()); // 获取点击的列
                    int rowIndex = showTable.rowAtPoint(e.getPoint()); // 获取点击的行

                    if (columnIndex == 1) {// 第0列时，执行代码
                        if (showTable.getValueAt(rowIndex, columnIndex) == null) { // 如果未初始化，则设置为false
                            showTable.setValueAt(false, rowIndex, columnIndex);
                        }

                        if (((Boolean) showTable.getValueAt(rowIndex, columnIndex)).booleanValue()) { // 原来选中
                            showTable.setValueAt(false, rowIndex, 1); // 点击后，取消选中
                            selectedTables.remove((String) showTable.getValueAt(rowIndex, columnIndex + 1));
                        } else {// 原来未选中
                            showTable.setValueAt(true, rowIndex, 1);
                            selectedTables.add((String) showTable.getValueAt(rowIndex, columnIndex + 1));
                        }
                        if (selectedTables.size() == 0) {
                            owner.disenabledNextStep();
                        } else {
                            owner.enabledNextStep();
                        }
                    }

                }
                owner.setSelectedTables(selectedTables);
            }
        });
        showTable.setRowHeight(20);
    }

    private List<DBTableModel> getTableCache() {
        List<DBTableModel> cache = null;
        try {
            cache = CacheUtil.getList(ConfigProperties.CACHE_STEP1_TABLE, DBTableModel.class);
        } catch (Exception e) {
            log.error("获取缓存失败", e);
        } // 获得缓存
        if (cache == null) {
            cache = new ArrayList<>();
        }
        return cache;
    }

    /**
     * 搜索输入框输入内容变化的监听方法
     * 
     * @Title addSearchActionListener
     * @author 吕凯
     * @date 2016年8月23日 下午3:21:00 void
     */
    private void addSearchTextListener() {
        searchText.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                textChange(e);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                textChange(e);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                textChange(e);

            }

            private void textChange(DocumentEvent e) {
                searchNum = 0;
                if (!tableList.isEmpty()) {
                    resetSearchTable();
                    if (searchText.getText().length() == 0) {
                        tableList.forEach(table -> addTableRow(table));
                        showlog("搜索到表" + tableList.size() + "条" + "，请选择表进行下一步操作！");
                    } else {
                        String searchkey = searchText.getText().toLowerCase();
                        tableList.stream().filter(table -> table.getTableName().toLowerCase().contains(searchkey)).forEach(table -> {
                            searchNum++;
                            DBTableModel tableShow = new DBTableModel();
                            tableShow.setTableName(table.getTableName());
                            tableShow.setDataSize(table.getDataSize());
                            tableShow.setTableComments(table.getTableComments());
                            addTableRow(tableShow);
                        });
                        owner.disenabledNextStep();
                        showlog("搜索到表" + searchNum + "条" + "，请选择表进行下一步操作！");
                    }
                }
            }
        });
    }

    /**
     * 设置表格宽度
     * 
     * @Title setTableColumWidth
     * @author 吕凯
     * @date 2016年8月23日 下午4:07:46 void
     */
    private void setTableColumWidth() {
        JTableUtil.fitTableColumns(showTable, new int[] { 30, 30, 300, 80, 120 });
        TableColumnModel tcm = showTable.getColumnModel();
        tcm.getColumn(1).setCellEditor(new CheckBoxCellEditor());
        tcm.getColumn(1).setCellRenderer(new CWCheckBoxRenderer());
    }

    public void searchDone() {
        searchBtn.setText("搜索表");
        canStopSearch = false;
        searchBtn.setEnabled(true);
    }

    public void addTableRow(DBTableModel table) {
        showTableModel.addRow(JTableModel.dbTable2jTableStep1(table, ++index));
    }

    /**
     * 添加table事件
     */
    private void addTableAction() {
        showTable.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger())
                    showMenu(e);
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger())
                    showMenu(e);
            }

            private void showMenu(MouseEvent e) {
//                int row = e.getY() / contentTable.getRowHeight();
//                filename = "fileName";
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        });

        // 监听事件
//        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
//            public void valueChanged(ListSelectionEvent e) {
//                if (e.getValueIsAdjusting()) {// 连续操作
//                    int columnIndex = table.getSelectedColumn();
//                    int rowIndex = table.getSelectedRow();
//                    if (columnIndex == 1) {
//                        filename =searchModel.getSearchPdfs().get(rowIndex/2).getAbsolatePath();
//                        System.out.println("正在打开文件 " + filename);
//                        openfile(filename);
//                    }
//                }
//            }
//        });
    }

}
